package com.ayoldi.podcastusbsync.configurator;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;

import com.ayoldi.podcastusbsync.downloader.FeedsDownloaderThread;
import com.ayoldi.podcastusbsync.downloader.FeedsDownloaderUtils;
import com.ayoldi.podcastusbsync.model.Configuration;
import com.ayoldi.podcastusbsync.model.Configuration.GlobalOptions;
import com.ayoldi.podcastusbsync.model.Configuration.UsbDeviceConfiguration;
import com.ayoldi.podcastusbsync.model.Configuration.UsbDeviceConfiguration.PodcastFeed;
import com.ayoldi.podcastusbsync.synchronizer.USBDeviceCheckerThread;
import com.ayoldi.podcastusbsync.synchronizer.USBDeviceSynchronizer;

public class ConfigurationManager {

	static Logger LOG = Logger.getLogger(ConfigurationManager.class);
	
	Unmarshaller jaxbUnmarshaller;
	Marshaller jaxbMarshaller;
	
	public ConfigurationManager(){
		JAXBContext jaxbContext;
		try {
			jaxbContext = JAXBContext.newInstance(Configuration.class);
			jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			jaxbMarshaller=jaxbContext.createMarshaller();
			jaxbMarshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); 
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		 
		
	}
	
	public Configuration readConfig(File file) {

		Configuration configuration=null;
		try {
			configuration = (Configuration) jaxbUnmarshaller.unmarshal(file);
			LOG.info("Configuration loaded succesfully from file: "+file.getAbsolutePath());
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LOG.warn("Could not load configuration from file: "+file.getAbsolutePath());
		}
		
		
		return configuration;
	}	
	
	public boolean writeConfig (File file, Configuration configuration) {
		 
		try {
			jaxbMarshaller.marshal(configuration, file);
			LOG.info("Configuration saved succesfully to file: "+file.getAbsolutePath());
			return true;
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LOG.warn("Could not save configuration to file: "+file.getAbsolutePath());
			return false;
		}
		
		
		
	}
	
	
	
	

	
}
